<template>
  <div>
    <el-row>
      <el-col :span="4">
        <el-tree :data="companyList" node-key="id" ref="companyOrgTree" :expand-on-click-node="false" :default-expand-all="true" :highlight-current="true" :render-content="renderCompanyTree" :check-strictly="true" @check-change="handleCheckChange" @node-click="handleNodeClick">
        </el-tree>
      </el-col>
      <el-col :span="16">
        <el-card>
          <div>
            <el-form :inline="true" ref="form" :model="form" label-width="80px" class="demo-form-inline">
              <el-form-item label="角色名称">
                <el-input v-model="form.tenantName"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="mb-1" icon="el-icon-search" size="middle" @click="getRolePage">
                  查询
                </el-button>
                <!-- <el-button type="primary" class="mb-15" icon="el-icon-refresh" size="middle" @click="onRefresh">
                    重置
                  </el-button> -->
              </el-form-item>
            </el-form>
          </div>
          <el-table ref="multipleTable" :data="tableData" border style="width: 100%;" height="calc(100vh - 220px)" row-key="id" @select="handleSelect">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称" width="200">
            </el-table-column>
            <el-table-column prop="permissionNum" label="关联权限" width="100">
            </el-table-column>
            <el-table-column prop="menuNum" label="关联菜单数" width="100">
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.status==='1'">正常</el-tag>
                <el-tag type="danger" v-else>禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
          </el-table>
          <div style="margin-top: 25px;">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="params.pageNum" :page-sizes="[10, 20, 50]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-row style="margin-top: 10px;">
          <el-col :span="6">
            <!-- 测试 -->
          </el-col>
          <el-col :span="18">
            {{ getCurrentOrgName() }}
          </el-col>
          <el-col :span="24">
            当前已关联如下功能：
          </el-col>
        </el-row>
        <el-tree :data="menuTree" :props="props" node-key="id" :expand-on-click-node="false" :default-expand-all="true" style="margin-top: 20px;">
        </el-tree>
      </el-col>
    </el-row>
  </div>
</template>
  
<script>
import { getCompanyTree } from "@/api/company";
import { getRolePage, getRoleIdsByOrgId, setOrgRoleRel } from "@/api/role";
import { getMenuListByOrgId } from '@/api/menu'
export default {
  data () {
    return {
      form: {
        fileName: '',
        transStatus: ''
      },
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      tableData: [],
      companyList: [],
      orgItem: undefined,
      roleIds: [],
      menuTree: [],
      props: {
        label: 'menuName',
        children: 'children'
      },
    }
  },
  mounted () {
    this.getCompanyTree()
    this.getRolePage()
  },
  methods: {
    getCompanyTree () {
      const that = this
      getCompanyTree().then((res) => {
        if (res.status === 200) {
          that.companyList = res.data;
          if (this.companyList.length > 0) {
            that.orgItem = that.companyList[0]
            that.getRoleIdsByOrgId()
            that.getMenuListByOrgId()
            const id = that.companyList[0].id
            that.$refs.companyOrgTree.setCheckedKeys([id]);
          }
        } else {
          this.$message(res.message);
        }
      });
    },
    renderCompanyTree (h, { node, data, store }) {
      let fontSize = "14px"
      let textColor = 'black'
      if (node.checked) {
        textColor = 'blue'; // 选中时文字变为红色
      }
      let labelV = node.data.companyName === undefined ? node.data.orgName : node.data.companyName
      return h('span', [
        // h("i", {
        //   class: iconName, style: {
        //     fontSize: "14px"
        //   }
        // }),
        // h('span', '内层文本1'), h('span', '内层文本2'),
        h('span', {
          style: {
            fontSize: fontSize,
            color: textColor
          }
        }, labelV)
      ]);
    },
    handleCheckChange (data, checked, indeterminate) {
      if (checked && data.children && data.children.length > 0) {
        // 如果父节点被选中，手动取消子节点的选中状态
        data.children.forEach(child => {
          this.$refs.tree.setChecked(child.id, false);
        });
      }
    },
    handleNodeClick (data) {
      this.$refs.companyOrgTree.setCheckedKeys([data.id]);
      this.params.pageNo = 1
      this.orgItem = data
      this.getRolePage()
      this.getRoleIdsByOrgId()
    },
    getRolePage () {
      const params = { ...this.params }
      getRolePage(params).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data.records;
          this.total = res.data.total
        } else {
          this.$message(res.message);
        }
      });
    },
    handleSizeChange (row) {
      this.params.pageSize = row
      this.params.pageNo = 1
      this.getRolePage()
    },
    handleCurrentChange (row) {
      this.params.pageNo = row
      this.getRolePage()
    },
    getRoleIdsByOrgId () {
      const params = { orgId: this.orgItem.id }
      getRoleIdsByOrgId(params).then((res) => {
        if (res.status === 200) {
          this.roleIds = res.data;
        } else {
          this.$message(res.message);
        }
      });
    },
    handleSelect (selection, row) {
      const params = { orgId: this.orgItem.id, roleList: selection }
      setOrgRoleRel(params).then((res) => {
        if (res.status === 200) {
          // this.getRoleIdsByOrgId()
          this.$message({
            message: '配置成功',
            type: 'success'
          });
          this.getMenuListByOrgId()
        } else {
          this.$message(res.message);
        }
      });
    },
    getMenuListByOrgId () {
      const params = { orgId: this.orgItem.id }
      getMenuListByOrgId(params).then((res) => {
        if (res.status === 200) {
          this.menuTree = res.data;
        } else {
          this.$message(res.message);
        }
      });
    },
    getCurrentOrgName () {
      if (this.orgItem !== undefined) {
        return this.orgItem.companyName === undefined ? this.orgItem.orgName : this.orgItem.companyName
      } else {
        return ""
      }
    }
  },
  watch: {
    roleIds (newValue, oldValue) {
      if (newValue.length > 0 || newValue !== undefined) {
        const that = this;
        setTimeout(function () {
          that.tableData.forEach(item => {
            // 假设我们要默认选中id为2的行
            const rowToSelect = newValue.find(row =>
              row === item.id
            );
            if (rowToSelect) {
              that.$refs.multipleTable.toggleRowSelection(item);
            }
          })
        }, 50);
      }
    }
  },
}
</script>
  
<style scoped>
::v-deep .el-table__body tr.current-row > td.el-table__cell,
.el-table__body tr.selection-row > td.el-table__cell {
  background-color: white !important;
  color: blue !important;
}
</style>